package com.econvent.common.conn;

import com.alibaba.druid.pool.DruidDataSource;
import com.econvent.common.conn.config.BaseConfig;
import com.econvent.common.conn.config.DruidConfig;
import com.econvent.common.conn.entity.BaseDataSourceProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;
import java.util.Properties;

@Slf4j
public class DruidDataSourceBuilder extends DataSourceBuilder {
    @Override
    public void buildDataSource(BaseDataSourceProperty baseDataSourceProperty) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(baseDataSourceProperty.getUser());
        dataSource.setPassword(baseDataSourceProperty.getPassword());
        dataSource.setUrl(baseDataSourceProperty.getUrl());
        dataSource.setName(baseDataSourceProperty.getDatasourcename());

        String driverClassName = baseDataSourceProperty.getDriverName();
        dataSource.setDriverClassName(driverClassName);

        this.dataSource = dataSource ;
    }

    @Override
    public void buildDataSourceConfig(BaseConfig dataSourceConfig) {
        DruidConfig druidConfig = (DruidConfig)dataSourceConfig ;

        Properties properties = new Properties();
        try {
            Map configDescib =  BeanUtils.describe(druidConfig) ;

            configDescib.forEach((propName, propValue) -> {
                if(null != propValue) {
                    properties.setProperty("druid." + propName, String.valueOf(propValue));
                }
            });

            // 设置属性
            ((DruidDataSource)dataSource).configFromPropety(properties);
        } catch (Exception e) {
            log.error("DruidDataSourceBuilder buildDataSourceConfig error, the exception is {} ", e);
            return  ;
        }
    }
}